import { useUserStore } from "@/stores/user";
import configObj from "@/config/index";
import { getToken, removeToken } from "./auth";
// #ifdef MP-WEIXIN
import { login } from "./auth";
// #endif
import { router, toast } from "./tools";
import cache from "./cache";

//根域名
const baseURL = configObj.baseURL;
// 添加拦截器
const httpInterceptor = {
  // 拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //  非 http 开头需拼接地址
    if (!options.url.startsWith("http")) {
      options.url = baseURL + options.url;
    }
    // 设置请求超时
    options.timeout = configObj.requestTimeout;
    // 添加小程序端请求头标识
    options.header = {
      ...options.header,
      "source-client": "miniapp",
    };
    // 添加 token 请求头标识
    const token = getToken();
    // 判断是否存在 token
    if (token) {
      options.header.appToken = token;
    }
  },
};
// 请求拦截器
uni.addInterceptor("request", httpInterceptor);
// 上传拦截器
uni.addInterceptor("uploadFile", httpInterceptor);

/**
 * 请求函数
 * @param  UniApp.RequestOptions
 * @returns Promise
 */
type Data<T> = {
  code: number;
  msg: string;
  data: T;
};
// 添加类型，支持泛型
export const request = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success(res) {
        let resData = res.data as Data<T>;
        // if (res.statusCode >= 200 && res.statusCode < 300) {
        if (resData.code == 200) {
          resolve(resData as Data<T>);
          return false;
        } else if (resData.code === 403) {
          // 清除token，重新登录
          removeToken();
          // #ifdef MP-WEIXIN
          login();
          // #endif
          // #ifdef H5
          uni.navigateTo({
            url: "/pages/login/login",
          });
          // #endif
          return false;
        } else if (resData.code == 500) {
          // router('/pages/login/login');
          resolve(resData as Data<T>);
          return false;
        } else if (
          resData.code == 500 &&
          resData.msg == "用户已授权，请勿重复授权"
        ) {
          uni.showToast({
            title: "用户已授权，返回首页",
            icon: "none",
            mask: true,
            success: () => {
              // 用户已授权跳转到首页
              setTimeout(() => {
                router("/pages/index/index", "switchTab");
              }, 1000);
            },
          });

          return false;
        } else {
          // cache.remove('token');
          toast(resData.msg);
          return false;
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: "none",
          title: "网络错误，换个网络试试",
        });
        reject(err);
      },
    });
  });
};

export const uploadImg = (file: any) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: "/Oss/upload",
      // #ifdef H5
      file,
      // #endif
      // #ifdef MP
      filePath: file,
      // #endif
      name: "file",
      // formData: {
      //   'user': 'test'
      // },
      success: (uploadFileRes) => {
        resolve(JSON.parse(uploadFileRes.data));
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
